<?php

use Workerman\Worker;

require_once './Autoloader.php';

$worker = new Worker('websocket://0.0.0.0:2015');
// 4个进程
$worker->count = 1;
$startPort = 3000;
// 每个进程启动后在当前进程新增一个Worker监听
$worker->onWorkerStart = function ($worker) {
    global $startPort;
    $port = $startPort + $worker->id;
    $worker->inner = new Worker('websocket://0.0.0.0:'.$port);
// 设置端口复用，可以创建监听相同端口的Worker（需要PHP>=7.0）
    $worker->inner->reusePort = true;
    $worker->inner->onMessage = function ($conn, $data) {
        echo $data.'----1111';
//        $conn->send(123456789);
    };
// 执行监听。正常监听不会报错
//    $inner_worker->listen();
    $worker->inner->listen();
};

$worker->onMessage = 'on_message';

function on_message($connection, $data)
{
    global $worker;
    print_r($data.'===='.$worker->id.PHP_EOL);
//    print_r($worker);

    echo $data.'----2222';
    $worker->inner->connections[array_rand($worker->inner->connections)]->send(123456);

    $connection->send("hello\n");

}

$worker->onConnect = function ($connection) {

};


// 运行worker
Worker::runAll();